#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-12-31 17:35 
# @Author : Z_Sprite
# @File : excel2csv.py 
# @Desc
import sys
import xlrd
import csv
from os import system


def read_excel(excel_name):
    work_book=xlrd.open_workbook("workbook/"+excel_name)
    table=work_book.sheet_by_index(0)#读取第一个sheet
    nrows=table.nrows
    ncols=table.ncols

    for rows_read in range(0,nrows):
        row_value=[]
        for cols_read in range(ncols):
            #获取单元格数据类型
            ctype=table.cell(rows_read,cols_read).ctype
            nu_str=table.cell(rows_read,cols_read).value

            # 检查并替换回车符和换行符
            if isinstance(nu_str, str):
                nu_str = nu_str.replace('\n','\\n').replace('\r\n', '\\n')

            # 判断返回类型
            # 0 empty,1 string, 2 number(都是浮点), 3 date, 4 boolean, 5 error
            # 是2（浮点数）的要改为int
            if ctype==2:
                nu_str=int(nu_str)
            row_value.append(nu_str)
        yield row_value

def csv_from_excel(excel_file:str):
    if excel_file.find(".xlsx")==-1:
        temp=excel_file.replace(".xls","")
    else:
        temp=excel_file.replace(".xlsx","")

    your_csv_file=open(''.join([temp,'.csv']),"w",encoding='utf8',newline="")
    wr=csv.writer(your_csv_file)

    for row_value in read_excel(excel_file):
        wr.writerow([entry for entry in row_value])
    your_csv_file.close()

if __name__ == '__main__':
    csv_from_excel(sys.argv[1])